<?php
namespace app\api\controller\vppz;


use think\Cache;


use \app\admin\model\vppz\Community as CommunityModel;
use \app\admin\model\vppz\MedicalStaff as MedicalStaffModel;
use \app\admin\model\vppz\StaffSchedules as StaffSchedulesModel;
use \app\admin\model\vppz\StaffTimeConfig as StaffTimeConfigModel;
use \app\admin\model\vppz\HomeServiceOrders as HomeServiceOrdersModel;
use \app\admin\model\vppz\HealthPackage as HealthPackageModel;
use \app\admin\model\vppz\PackageService as PackageServiceModel;
use \app\admin\model\vppz\User as UserModel;

use \addons\vppz\library\Vpower;

class Community extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->CommunityModel = new CommunityModel;
        $this->MedicalStaffModel = new MedicalStaffModel;
        $this->timeComfigModel = new StaffTimeConfigModel;
        $this->StaffSchedulesModel = new StaffSchedulesModel;
        $this->HomeServiceOrdersModel = new HomeServiceOrdersModel;
        $this->HealthPackageModel = new HealthPackageModel;
        $this->PackageServiceModel = new PackageServiceModel;
        $this->UserModel = new UserModel;
    }


    /**
     * 医护上门首页
     */
    public function index(){
		$area=$this->_area;
        $lng = input('lng');
        $lat = input('lat');
        $is_kangyang = input('is_kangyang',1);
        $res = $this->CommunityModel->where('area_id','=',$area['id']);

        $res = $res->whereLike('type','%'.$is_kangyang.'%');
        $res = $res->whereNull("deletetime")
            ->order(['weigh'=>'DESC','createtime'=>'desc'])->select();
        $resDistance = [];
        if(empty($res) === FALSE){
            foreach ($res as $bk=>$bj){
                $res[$bk]['createtime'] = date('Y-m-d H:i:s',$res[$bk]['createtime']);
                //获取社区医生信息
                if ($is_kangyang == 1) {
                    $doctors = $this->MedicalStaffModel->whereNull("deletetime")->where("hospital_id", '=', $bj['id'])->select();
                    $res[$bk]['doctors'] = $doctors;
                }else if ($is_kangyang == 2){
                    $package = $this->HealthPackageModel->whereNull("deletetime")->where("community_id",'=',$bj['id'])->select();
                    $res[$bk]['package'] = $package;
                }

                $distance = \Tools::getDistance($lng,$lat,$bj['lng'],$bj['lat']);
                array_push($resDistance,$distance);
                $res[$bk]['distance'] = sprintf("%.2f",$distance/1000);
            }
            array_multisort($resDistance,SORT_ASC,$res);
        }
		$this->success('',$res);
    }
    //社区详情
    public function detail(){
        $id = input("id",'');
        if(empty($id)){
            $this->error('参数有误');
        }
        $detail = $this->CommunityModel::get(['id'=>$id]);
        if(empty($detail)) $this->error('记录不存在');
        $service_hours = json_decode($detail['service_hours']);
        $times = $this->timeComfigModel->whereIn('id',$service_hours)->whereNull('delete_time')->order('start','asc')->select();
        $resTime = [];
        if(empty($times) === FALSE){
            foreach ($times as &$v){
                array_push($resTime,$v['start'].'-'.$v['end']);
            }
        }
        $staff = $this->MedicalStaffModel->where('hospital_id',$id)->select();
        $detail['staff'] = $staff;
        $detail['service_hours'] = $resTime;
        $this->success('',$detail);
    }
    //获取社区医院预约时间
    public function getTime(){
        $area=$this->_area;
        $doctor_id = input("doctor_id",'');
        $community = input("community_id",'');
        if(empty($doctor_id) || empty($community)){
            $this->error('参数有误');
        }
        //获取社区医院时间
        $service_hours = $this->CommunityModel->where('id','=',$community)->value('service_hours');
        $service_hours = json_decode($service_hours,true);
        $times = $this->timeComfigModel->whereIn('id',$service_hours)->select();
        $resData = [];
        if(empty($times) === FALSE){
            foreach ($times as $timeKey => $timeValue){
                array_push($resData, $timeValue['start'] . '-' . $timeValue['end']);
            }
        }
        $doctorTime = [];
        $doctorTime = $this->StaffSchedulesModel->where('staff_id',$doctor_id)->select();
        $time = [];
        if(empty($doctorTime) === FALSE){
            foreach ($doctorTime as &$v){
                $nowtime = array(
                    'date'=>$v['schedule_date'],
                    'time'=>$v['start_time'].'-'.$v['end_time']
                );
                array_push($time,$nowtime);
            }
        }
        $data = array(
            'time'=>$resData,
            'doctor_time'=>$time
        );
        //获取医生已约时间
        $this->success('',$data);
    }
    //todo 提交预约
    public function appintment(){
        $json = file_get_contents("php://input");
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        //查询医生是否绑定用户
        $doctorId = '';
        $doctor = $this->MedicalStaffModel->where(array(
            'id'=>$data['doctorId']
        ))->whereNull('deletetime')->find();
        if(empty($doctor) || empty($doctor['user_id'])){
            $this->error('医生状态异常，请联系所在社区确认');
        }else{
            $doctorId = $doctorId['user_id'];
        }
        $orderdata = array(
            'order_no'=>uniqid('order_', true),
            'user_id'=>$this->_mine['id'],
            'staff_id'=>$doctorId,
            'hospital_id'=>$data['communityId'],
            'service_address'=>$data['addressInfo']['address'],
            'longitude'=>$data['addressInfo']['longitude'],
            'latitude'=>$data['addressInfo']['latitude'],
            'scheduled_time'=>$data['appointmentDate'].' '.$data['timeSlot'],
            'price'=>$data['price']??0,
            'status'=>$data['status'],
            'patient_notes'=>$data['serviceContent'],
            'patient_name'=>$data['patientInfo']['name'],
            'patient_sex'=>$data['patientInfo']['gender'],
            'patient_age'=>$data['patientInfo']['age'],
            'contect_name'=>$data['contactInfo']['name'],
            'contect_phone'=>$data['contactInfo']['phone']
        );
        $time = explode('-',$data['timeSlot']);
        if($data['appointmentDate'] == date('Y-m-d')){
            if(intval($time[0]) < date('H')){
                $this->error('预约时间不能小于当前时间');
            }
        }
        $this->HomeServiceOrdersModel->startTrans();
        $opera = array();

        $ret[]=$this->HomeServiceOrdersModel->save($orderdata);
		$orderdata['id'] = $this->HomeServiceOrdersModel->id;
        $ret[]=$this->StaffSchedulesModel->save(array(
            'staff_id'=>$data['doctorId'],
            'schedule_date'=>$data['appointmentDate'],
            'start_time'=>$time[0],
            'end_time'=>$time[1]
        ));
		if(\Tools::checkArrayResult($ret)){
			$this->HomeServiceOrdersModel->commit();
            $this->success('提交成功',$ret);
		}else{
            $this->HomeServiceOrdersModel->rollback();
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }

    public function login(){
        $username = input("username",'');
        $password = input("password",'');
        if(empty($username) || empty($password)){
            $this->error('参数有误');
        }
        $user = $this->MedicalStaffModel::get(['login_name' => $username]);
        if (!$user) {
            $this->error('账号不存在');
            return false;
        }
        if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
            $this->error('密码有误');
            return false;
        }
        $user->user_id = $this->_mine['id'];
        $user->updatetime = time();
        $ret = $user->save();
        //绑定账号
        $nowUser = $this->UserModel::get(['id'=>$this->_mine['id']]);
        $nowUser->type = 3;
        $nowUser->save();
        //获取医生已约时间
        $this->success('',$ret);
    }
    //获取预约记录
    public function appintmentListNum(){
        $pendingCount = $this->HomeServiceOrdersModel->where(
            [
                'staff_id'=>$this->_mine['id']
            ]
        )->whereIn('status','pending')
            ->whereNull("deletetime")->count();

        $confirmCount = $this->HomeServiceOrdersModel->where(
            [
                'staff_id'=>$this->_mine['id']
            ]
        )->whereIn('status','confirmed,completed')
            ->whereNull("deletetime")->count();
        $this->success('',array(
            'pendingCount'=>$pendingCount,
            'confirmedCount'=>$confirmCount
        ));
    }
    public function appintmentList(){
        $page_no = input("page_no",1);
        $page_size = input("page_size",20);
        $status = input("status",'pending');
        if($status != 'pending'){
            $status = 'confirmed,completed';
        }
        $service = $this->HomeServiceOrdersModel->where(
            [
                'staff_id'=>$this->_mine['id']
            ]
        )->whereIn('status',$status)
            ->whereNull("deletetime")
            ->limit(($page_no-1)*$page_size,$page_size)
            ->select();

        $this->success('',array(
            'Services'=>$service
        ));
    }
    //确认接收预约
    public function confirmOrder(){
        $id = input("id",'');
        if(empty($id)){
            $this->error('参数有误');
        }
        $service = $this->HomeServiceOrdersModel::get(['id'=>$id]);
        if(empty($service)) $this->error('预约记录不存在');
        $service->status = 'confirmed';
        $service->updatetime = time();
        $ret = $service->save();
        $this->success('',$ret);
    }

    //完成接收预约
    public function finishOrder(){
        $id = input("id",'');
        if(empty($id)){
            $this->error('参数有误');
        }
        $service = $this->HomeServiceOrdersModel::get(['id'=>$id]);
        if(empty($service)) $this->error('预约记录不存在');
        $service->status = 'completed';
        $service->updatetime = time();
        $ret = $service->save();
        $this->success('',$ret);
    }
    //预约详情
    public function serviceDetail(){
        $id = input("id",'');
        if(empty($id)){
            $this->error('参数有误');
        }
        $service = $this->HomeServiceOrdersModel::get(['id'=>$id]);
        if(empty($service)) $this->error('预约记录不存在');
        $service['createtime'] = date('Y-m-d H:i:s',$service['createtime']);
        $this->success('',$service);
    }
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
}
